package com.openmind.pichosting.datasources.aspect;

import com.openmind.pichosting.datasources.DataSourceNames;
import com.openmind.pichosting.datasources.DynamicDataSource;
import com.openmind.pichosting.datasources.annotation.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * DataSourceAspect 多数据源，切面处理类
 *
 * @author zhoujunwen
 * @date 2019-09-04
 * @time 22:05
 * @desc
 */
@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {
    @Override
    public int getOrder() {
        return 1;
    }

    @Pointcut("@annotation(com.openmind.pichosting.datasources.annotation.DataSource)")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource == null) {
            DynamicDataSource.setDataSource(DataSourceNames.MYSQL);
            log.info("set datasource is {}", DataSourceNames.MYSQL);
        } else {
            DynamicDataSource.setDataSource(dataSource.name());
            log.info("set datasource is {}", dataSource.name());
        }

        try {
            return joinPoint.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }

}
